﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Crow.Library.Bootstrappers;
using Crow.Library.Common;
using Crow.Library.Foundation;
using Crow.Library.Foundation.Hosting;

namespace Crow.Library.Host.AspNet
{
    public class CrowHostBootstrapper : Bootstrappers.Bootstrapper
    {
        public CrowHostBootstrapper()
            : base(new DefaultAssemblyLoader())
        {
        }

        public static ICrowHttpHost Host { get; private set; }

        protected override void LoadModules(IEnumerable<Assembly> assemblies)
        {
            base.LoadModules(assemblies);

            var startHost = CrowCore.Configuration.Get<bool>(Strings.Configuration.StartHost);
            if (startHost)
            {
                StartHost();
            }
        }

        private void StartHost()
        {
            Host = CrowHost.ConfigureHost(CrowCore.Container);
            var business = Container.GetExports<IHostBusiness>();
            foreach (var type in business.Select(item => item.Value.GetType().GetInterfaces().FirstOrDefault(t => t != typeof (IHostBusiness))))
            {
                type.ThrowIfNull("type");

                Host.Host(type);
            }
            Host.Start();
        }

        protected override void UnloadModules()
        {
            if (Host != null)
            {
                Host.Dispose();
            }
        }
    }
}